﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;
using WebCrawlerTools.page;
using WebCrawlerTools.search;
using WebCrawlerTools.data;

namespace WebCrawlerTools
{
    public partial class MainForm : Form
    {
        private DataCenter dataCenter;
        private SEngine enginer = SEngine.getSEngine();
        private Page currentPage;

        private ArrayList sLines = new ArrayList();

        public MainForm()
        {
            InitializeComponent();
        }

        private void btn_url_Click(object sender, EventArgs e)
        {
            SEngine.getSEngine().Page = currentPage;
            Log.Inst().Path = dataCenter.BasicInfo.DataPath + "\\" + currentPage.Name;
            SEngine.getSEngine().DataCenter = dataCenter;
            SEngine.getSEngine().Start();
        }

        #region Onload
        private void overed(object sender, EventArgs e)
        {
            htmlwin.Text = SEngine.getSEngine().Source;
        }

        private void display(object sender, EventArgs e)
        {
            sLines = enginer.Result.Data;
            datawin.Columns.Clear();
            datawin.Items.Clear();
            foreach (String title in enginer.Result.Title.Data)
            {
                datawin.Columns.Add(title, 50, HorizontalAlignment.Left);
            }

            foreach (SLine sl in sLines)
            {
                ListViewItem li = datawin.Items.Add((String)sl.Data[0]);
                for (int i = 1; i < sl.Data.Count; i++)
                {
                    li.SubItems.Add((String)sl.Data[i]);
                }
            }
        }

        private void loadlast(object sender, EventArgs e)
        {
            goNextPage.Enabled = true;         
        }

        private void startsubpage(object sender, EventArgs e)
        {
            if (null != currentPage && currentPage.PageType == PPageType.HOME_PAGE)
            {
                currentPage = ((PHomePage)currentPage).SubPage;
                SEngine.getSEngine().Page = currentPage;
                UI_Update_Page(true, currentPage);
            }
        }
        #endregion

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            UI_Update_All(false);
            DataCenter.Store(dataCenter);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            MyWebBrower.Web = webwin;
            this.webwin.ProgressChanged += new System.Windows.Forms.WebBrowserProgressChangedEventHandler(enginer.Net.OnOpen);

            enginer.Net.Done += new EventHandler(this.overed);
            enginer.Net.Done += new EventHandler(this.display);
            enginer.Net.Done += new EventHandler(this.loadlast);

            enginer.AllPageComplate += new EventHandler(this.startsubpage);

            dataCenter = DataCenter.Load();
            Log.Inst().Path = dataCenter.BasicInfo.DataPath;
            UI_Update_All(true);

        }

        #region UI_Update
        private void UI_Update_Page(bool IsLoad,Page page)
        {
            if (page == null)
                return;
            if (IsLoad)
            {
                txt_url.Text = page.Url;
                tempwin.Text = page.Template.Replace("\n", "\r\n");
                if (page.Loop != null)
                {
                    if (page.Loop.Type == LoopType.URL)
                    {
                        rdo_url.Checked = true;
                    }
                    else
                    {
                        rdo_js.Checked = true;
                    }
                    txt_url_tmpl.Text = page.Loop.Template;
                    PNextRule rule = page.Loop.Rule;
                    if (rule != null)
                    {
                        txt_start_pos.Text = String.Format("{0}", rule.Start);
                        txt_end_pos.Text = String.Format("{0}", rule.End);
                        txt_step.Text = String.Format("{0}", rule.Step);
                    }
                    else
                    {
                        txt_start_pos.Text = "0";
                        txt_end_pos.Text = "0";
                        txt_step.Text = "0";
                    }
                }
                else
                {
                    txt_url_tmpl.Text = "";
                    rdo_url.Checked = true;
                    txt_start_pos.Text = "0";
                    txt_end_pos.Text = "0";
                    txt_step.Text = "0";
                }
            }
            else
            {
                page.Url = txt_url.Text;
                page.Template = tempwin.Text.Replace("\r", "");
                page.Loop = new PLoop();
                if (rdo_url.Checked)
                {
                    page.Loop.Type = LoopType.URL;
                }
                else
                {
                    page.Loop.Type = LoopType.JavaScript;
                }
                page.Loop.Template = txt_url_tmpl.Text;
                PNextRule para = new PNextRule();
                if (!String.IsNullOrEmpty(txt_start_pos.Text))
                {
                    para.Start = int.Parse(txt_start_pos.Text);
                }
                if (!String.IsNullOrEmpty(txt_end_pos.Text))
                {
                    para.End = int.Parse(txt_end_pos.Text);
                }
                if (!String.IsNullOrEmpty(txt_step.Text))
                {
                    para.Step = int.Parse(txt_step.Text);
                }
                page.Loop.Rule = para;

            }
        }
        private void UI_Update_All(bool IsLoad)
        {
            if (IsLoad)
            {
                treeView1.BeginUpdate();
                treeView1.Nodes.Clear();
                foreach (PHomePage page in dataCenter.PHomePages)
                {
                    TreeNode node = treeView1.Nodes.Add(page.Name);
                    node.Tag = page;
                    node.Nodes.Add("Sub Page");
                    node.Nodes[0].Tag = page.SubPage;
                }
                treeView1.EndUpdate();
                treeView1.ExpandAll();
                if (dataCenter.PHomePages != null && dataCenter.PHomePages.Count >= 1)
                {
                    currentPage = (PHomePage)dataCenter.PHomePages[0];
                    UI_Update_Page(IsLoad, currentPage);
                }
            }
            else
            {
                //UI_Update_Page(IsLoad, dataCenter.Page);
            }
        }

        private void UI_Leave(object sender, EventArgs e)
        {
            UI_Update_Page(false, currentPage);
        }


        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                currentPage = (Page)treeView1.SelectedNode.Tag;
                UI_Update_Page(true, currentPage);
            }
        }
        #endregion

        #region Tree Operate
        private void btn_add_Click(object sender, EventArgs e)
        {
            DlgSiteInfo sitedlg = new DlgSiteInfo();
            if (sitedlg.ShowDialog() == DialogResult.OK)
            {
                PHomePage page = new PHomePage();
                page.Name = sitedlg.SiteName;
                page.SubPage = new PSubPage();
                page.SubPage.Name = "Sub Page";
                dataCenter.PHomePages.Add(page);

                treeView1.BeginUpdate();
                TreeNode node = treeView1.Nodes.Add(sitedlg.SiteName);
                node.Tag = page;

                node.Nodes.Add("Sub Page");
                node.Nodes[0].Tag = page.SubPage;

                treeView1.EndUpdate();
            }
        }

        private void btn_del_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                TreeNode node = treeView1.SelectedNode;
                if (node.Text == "Sub Page")
                {
                    if (treeView1.SelectedNode.Parent != null)
                    {
                        node = treeView1.SelectedNode.Parent;
                    }
                }
                if (MessageBox.Show(node.Text + "を削除しますか", "削除", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    treeView1.Nodes.Remove(node);
                }
            }
        }
        #endregion


        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DDataInfo.Store(dataCenter.DataInfo, saveFileDialog1.FileName);
            }
        }

        private void btn_next_page_Click(object sender, EventArgs e)
        {
            enginer.GoNextPage();
        }

        private void goNextPage_Tick(object sender, EventArgs e)
        {
            enginer.GoNextPage();
            goNextPage.Enabled = false;
        }

        private void btn_edit_Click(object sender, EventArgs e)
        {
            DlgSystem dlg = new DlgSystem();
            dlg.DataPath = dataCenter.BasicInfo.DataPath;
            if (string.IsNullOrEmpty(dlg.DataPath))
            {
                dlg.DataPath = System.Environment.CurrentDirectory;
            }
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                dataCenter.BasicInfo.DataPath = dlg.DataPath;
            }
        }
    }
}